/**
 * File: PersistContigIdxController.java
 * Created by: mhaimel
 * Created on: 17 Aug 2009
 * CVS:  $Id: PersistContigIdxController.java,v 1.1 2009/10/09 14:57:55 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.loader;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import uk.ac.ebi.curtain.controller.SingleSubmitController;
import uk.ac.ebi.curtain.service.IdentifierStore;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.data.ReadType;
import uk.ac.ebi.curtain.utils.io.AbstractIO.CompressionFormat;
import uk.ac.ebi.curtain.utils.io.impl.FileIO;

/**
 * @author mhaimel
 *
 */
public class PersistContigIdxController extends SingleSubmitController<Serializable, Serializable> {

	
	private static final char SEP_CHAR = '\t';
	
	@Override
	protected void singleSubmit(List<Serializable> inputList) {
		File c = getContext().currentFiles().getIndexFile(ReadType.Contig);
		persist(c,getContext().getContigIndex());	
		for(Serializable s : inputList){
			submit(s);
		}
	}
	
	private void persist(File file, IdentifierStore<String, Integer> identifierStore){
		FileIO io = new FileIO(file);
		io.setCompression(CompressionFormat.Gzip);
		Iterable<String> keys = identifierStore.getKeys();
		BufferedWriter out = null;
		try{
			out = io.getBufferedWriter();
			for(String s : keys){
				Integer id = identifierStore.getIdentifier(s);
				out.write(id.toString());
				out.write(SEP_CHAR);
				out.write(s);
				out.newLine();
			}			
		} catch (IOException e) {
			throw new CurtainUncheckedException(e);
		}finally{
			FileIO.closeQuietly(out);
		}		
	}


}
